<template>
	<view class="merchant-detail">
		<g-navbar title="商户详情" />
		<view class="main" v-if="merchantDetail">
			<view class="merchant-info-container">
				<view class="merchant-info-top-wrapper">
					<view class="merchant-phone">
						{{merchantDetail.merchant_name}}/{{merchantDetail.phone}}
					</view>
					<!-- 	<view class="merchant-status">
						正常
					</view> -->
				</view>
				<view class="merchant-info-bottom-wrapper">
					所属代理：{{merchantDetail.agent_phone+'/'+merchantDetail.agent_name}}
				</view>
			</view>

			<view class="merchant-amount-container">
				<view class="amount-item">
					<view class="amont-value">
						<g-auto-zoom-text>￥{{merchantDetail.month_trade}}</g-auto-zoom-text>
					</view>
					<view class="amount-label">
						本月交易量
					</view>
				</view>
				<view class="amount-item">
					<view class="amont-value">
						<g-auto-zoom-text>￥{{merchantDetail.total_amount}}</g-auto-zoom-text>
					</view>
					<view class="amount-label">
						累计交易量
					</view>
				</view>
			</view>

			<view class="merchant-statistics-container">
				<view class="merchant-statistics-top">
					<view class="title">
						交易金额趋势
					</view>
					<view class="tabs-wrapper">
						<custom-tabs type="c1" :value="current" :current="current" @change="onChange" :tabSpacing="34">
							<custom-tab-pane style="width:100%" :label="item.label" name="c1_2"
								v-for="item,index in statisticsOptionsList" :key="index">
								<view class="label amount">销售额</view>
								<view class="chart-wrapper">
									<qiun-data-charts type="column" :opts="columnOptions"
										:chartData="columnChartData" />
								</view>
								<view class="label date">日期</view>
							</custom-tab-pane>
						</custom-tabs>
					</view>
				</view>
			</view>

			<view class="merchant-statistics-container">
				<view class="merchant-statistics-top">
					<view class="title">
						交易量趋势
					</view>
					<view class="tabs-wrapper">
						<custom-tabs type="c1" :value="current" :current="current" @change="onChange" :tabSpacing="34">
							<custom-tab-pane style="width:100%" :label="item.label" name="c1_2"
								v-for="item,index in statisticsOptionsList" :key="index">
								<view class="label amount">交易量</view>
								<view class="chart-wrapper">
									<qiun-data-charts type="line" :opts="radarChartOptions"
										:chartData="lineChartData" />
								</view>
								<view class="label date">日期</view>
							</custom-tab-pane>
						</custom-tabs>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script lang="ts" setup>
	import dayjs from 'dayjs';
	import {
		STATISTICS_DATE_STATUS,
		IStatisticsOptions,
		IDateItem,
		IMerchantDetail,
		ITabsChangeEvent,
		IRequestOptions
	} from './types';
	import { onLoad, onReady } from '@dcloudio/uni-app';
	import { reactive, Ref, ref, computed } from "vue";
	import { useStore } from 'vuex';
	import REST_URL from '@/http/http.restUrl';
	import { GET_STORE_USERINFO } from '@/store/gettersType';

	const store = useStore();

	const merchantDetail : Ref<IMerchantDetail | null> = ref(null);

	const baseChartOptions = {
		color: ["#FAC858", "#EE6666", "#FAC858", "#EE6666", "#73C0DE", "#3CA272", "#FC8452", "#9A60B4", "#ea7ccc"],
		update: true,
		enableScroll: false,
		legend: {},
		xAxis: {
			disableGrid: true
		},
		yAxis: {
			data: [
				{
					min: 0,
					// max:1000,
				}
			]
		},
	}


	const columnOptions = {
		...baseChartOptions,
		extra: {
			column: {
				type: "group",
				width: 30,
				activeBgColor: "#000000",
				activeBgOpacity: 0.08,
				linearType: "custom",
				seriesGap: 5,
				linearOpacity: 0.5,
				barBorderCircle: true,
				customColor: [
					"#FA7D8D",
					"#EB88E2"
				]
			}
		}
	}


	const radarChartOptions = {
		...baseChartOptions,
		extra: {
			line: {
				type: "straight",
				width: 2,
				activeType: "hollow"
			}
		}
	}


	const current : Ref<number> = ref(0);

	const currentDateList = computed(() => {
		const currentItem = statisticsOptionsList[current.value];
		const dateList : string[] = [];
		switch (currentItem.status) {
			case STATISTICS_DATE_STATUS.WEEK:
				for (let key in currentItem.list) {
					dateList.unshift(dayjs(currentItem.list[key].date).format('M-DD'))
				}
				return dateList
			case STATISTICS_DATE_STATUS.HALF_YEAR:
				for (let key in currentItem.list) {
					dateList.unshift(dayjs(currentItem.list[key].date).format('YY-MM'))
				}
				return dateList
		}
	})

	const currentCount = computed(() => {
		const currentItem = statisticsOptionsList[current.value];
		const countList : number[] = [];
		switch (currentItem.status) {
			case STATISTICS_DATE_STATUS.WEEK:
				for (let key in currentItem.list) {
					countList.unshift(currentItem.list[key].count)
				}
				return countList
			case STATISTICS_DATE_STATUS.HALF_YEAR:
				for (let key in currentItem.list) {
					countList.unshift(currentItem.list[key].count)
				}
				return countList
		}
	})


	const currentAmount = computed(() => {
		const currentItem = statisticsOptionsList[current.value];
		const amountList : number[] = [];
		switch (currentItem.status) {
			case STATISTICS_DATE_STATUS.WEEK:
				for (let key in currentItem.list) {
					amountList.unshift(currentItem.list[key].amount)
				}
				return amountList
			case STATISTICS_DATE_STATUS.HALF_YEAR:
				for (let key in currentItem.list) {
					amountList.unshift(currentItem.list[key].amount)
				}
				return amountList
		}
	})


	const modelSN : Ref<string> = ref('');


	onLoad((e) => {
		modelSN.value = e.model_sn;
	})

	onReady(async () => {
		await uni.loginManger.$interceptor;
		await getMerchantDetail();
	})




	const statisticsOptionsList : IStatisticsOptions[] = reactive([
		{
			label: '近七日',
			status: STATISTICS_DATE_STATUS.WEEK,
			dateCount: 7,
			isUpdate: false,
			list: {}
		},
		{
			label: '近半年',
			status: STATISTICS_DATE_STATUS.HALF_YEAR,
			dateCount: 6,
			isUpdate: false,
			list: {}
		}
	])



	const statisticsOptionsListInit = (dateList : { [propname : string] : IDateItem } = {}) : void => {
		for (let item of statisticsOptionsList) {
			const dateCount = item.dateCount;
			switch (item.status) {
				case STATISTICS_DATE_STATUS.WEEK:
					if (item.isUpdate) {
						break;
					}
					for (let i = 0; i < dateCount; i++) {
						const dateStr : string = dayjs().subtract(i, 'day').startOf(i === dateCount - 1 ? 'day' : 'second').format('YYYY-MM-DD');
						const temp : IDateItem = {
							date: dateStr,
							amount: 0,
							count: 0,
						}
						item.list[dateStr] = dateList[dateStr] ? dateList[dateStr] : temp;
					}
					break;
				case STATISTICS_DATE_STATUS.HALF_YEAR:
					if (item.isUpdate) {
						break;
					}
					for (let i = 0; i < dateCount; i++) {
						const dateStr : string = dayjs().subtract(i, 'month').startOf(i === dateCount - 1 ? 'month' : 'second').format('YYYY-MM-DD');
						const temp : IDateItem = {
							date: dateStr,
							amount: 0,
							count: 0,
						}
						item.list[dateStr] = dateList[dayjs(dateStr).format('YYYY-MM')] ? dateList[dayjs(dateStr).format('YYYY-MM')] : temp;
					}
					break;
			}
		}
	}

	statisticsOptionsListInit();


	const columnChartData = ref({
		categories: currentDateList.value,
		series: [
			{
				name: "交易金额",
				data: currentAmount.value
			},
		]
	});

	const lineChartData = ref({
		categories: currentDateList.value,
		series: [
			{
				name: "交易数量",
				data: currentCount.value
			}
		]
	});

	const onChange = (e : ITabsChangeEvent) => {
		current.value = e.value;
		getMerchantDetail();
	}

	const resetChart = () => {
		columnChartData.value = {
			categories: currentDateList.value,
			series: [
				{
					name: "交易金额",
					data: currentAmount.value
				}
			]
		}
		lineChartData.value = {
			categories: currentDateList.value,
			series: [
				{
					name: "交易数量",
					data: currentCount.value
				}
			]
		}
	}

	const getMerchantDetail = async () : Promise<void> => {
		const currentIndex = current.value;
		console.log(statisticsOptionsList[currentIndex].isUpdate)
		if (statisticsOptionsList[currentIndex].isUpdate) {
			resetChart();
			return
		}
		let options : IRequestOptions = {
			customer_id: store.getters[GET_STORE_USERINFO].id,
			model_sn: modelSN.value,
		}
		switch (statisticsOptionsList[currentIndex].status) {
			case STATISTICS_DATE_STATUS.WEEK:
				options = {
					customer_id: store.getters[GET_STORE_USERINFO].id,
					model_sn: modelSN.value,
					end_week: statisticsOptionsList[currentIndex].list[Object.keys(statisticsOptionsList[currentIndex].list)[0]].date,
					start_week: statisticsOptionsList[currentIndex].list[Object.keys(statisticsOptionsList[currentIndex].list).slice(-1)[0]].date,
				}
				break;
			case STATISTICS_DATE_STATUS.HALF_YEAR:
				options = {
					customer_id: store.getters[GET_STORE_USERINFO].id,
					model_sn: modelSN.value,
					end_year: statisticsOptionsList[currentIndex].list[Object.keys(statisticsOptionsList[currentIndex].list)[0]].date,
					start_year: statisticsOptionsList[currentIndex].list[Object.keys(statisticsOptionsList[currentIndex].list).slice(-1)[0]].date,
				}
				break;
		}
		console.log(options);
		const result : IMerchantDetail = (await uni.http.POST(REST_URL.getMerchantDetail, options)).data;
		merchantDetail.value = result;
		statisticsOptionsListInit(statisticsOptionsList[currentIndex].status === STATISTICS_DATE_STATUS.WEEK ? result.week_trade : result.year_trade);
		statisticsOptionsList[currentIndex].isUpdate = true;
		console.log(statisticsOptionsList)
		resetChart();
	}
</script>

<style scoped lang="scss">
	@import "./merchantDetail.scss";
</style>